<template>
    <div>
        <div class="main-head flex-between container-fluid">
            <div class="title">
                <h1 v-text="$t('pro.campaignsServe.edit')+' SSP'"></h1>
            </div>
        </div>
        <div class="content container-fluid">
            <div class="breadcrumb">
                <a-breadcrumb :routes="routes">
                    <template slot="itemRender" slot-scope="{route, params, routes}">
            <span v-if="routes.indexOf(route) === routes.length - 1">
              {{route.breadcrumbName}}
            </span>
                        <router-link v-else :to="route.path">
                            {{route.breadcrumbName}}
                        </router-link>
                    </template>
                </a-breadcrumb>
            </div>
            <div class="portlet">
                <div class="grid grid-col-3">
                    <div>
                        <div class="grid-item-title">
                            <h3>{{ $t('pro.ssp.sspInfo') }}</h3>
                        </div>
                        <div class="addtransaction-form">
                            <a-spin :spinning="loading">
                                <a-form
                                    :form="form"
                                    layout="vertical"
                                    @submit="handleSubmit"
                                >
                                    <a-form-item :label="$t('pro.settings.navsColumns')[0].title">
                                        <a-input v-decorator="['name',
                                                   {rules:[{
                                                    validator: validateSSPName
                                                  }]}]"
                                                  :disabled="!isAdd"/>
                                    </a-form-item>

                                    <a-form-item :label="$t('pro.ssp.trafficCategory')">
                                        <a-select
                                            showSearch
                                            style="width: 100%;"
                                            v-decorator="['trafficCategory', { initialValue: textList[0] }]"
                                            :filterOption="filterOption"
                                        >
                                            <a-select-option
                                                v-for="(item, index) in textList"
                                                :key="index"
                                                :value="item"
                                                @click="typeChange(item)"
                                            >{{item}}</a-select-option>
                                        </a-select>
                                    </a-form-item>

                                    <a-form-item :label="$t('pro.ssp.region')">
                                        <a-select
                                                style="width: 100%;"
                                                v-decorator="['region', { initialValue: bidList[0].from }]"
                                        >
                                            <a-select-option
                                                    v-for="(item, index) in bidList"
                                                    :key="index"
                                                    :value="item.from"
                                            >{{item.from}}</a-select-option>
                                        </a-select>
                                    </a-form-item>

                                    <!--<a-form-item v-if="isEIkey" :label="'e_key'">
                                        <a-input v-decorator="['eKey']"/>
                                    </a-form-item>

                                    <a-form-item v-if="isEIkey" :label="'i_key'">
                                        <a-input v-decorator="['iKey']"/>
                                    </a-form-item>-->

                                    <a-form-item :label="''">
                                        <!-- 是否编码 -->
                                        <a-checkbox v-decorator="['usesEncodedAdm', { valuePropName: 'checked' }]">
                                            <a-tooltip :title="$t('pro.formItem.usesEncodedAdm')">
                                                {{ $t('pro.ssp.usesEncodedAdm') }} <a-icon type="question-circle-o" style="font-size: 0.3rem;margin-top: -2px"/>
                                            </a-tooltip>
                                        </a-checkbox>

                                        <a-checkbox v-decorator="['isActive', { valuePropName: 'checked', initialValue: true, }]">
                                            {{ $t('pro.ssp.columns')[2].title }}
                                        </a-checkbox>
                                    </a-form-item>

                                    <!-- 隐私字段 不是新增情况下才显示 -->
                                    <a-form-item label="id" v-if="!isAdd" v-show="false">
                                        <a-input v-decorator="['id']"></a-input>
                                    </a-form-item>

                                    <a-form-item>
                                        <a-button type="primary" html-type="submit">{{ $t('pro.public.buttonSave') }}</a-button>
                                    </a-form-item>

                                </a-form>
                            </a-spin>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    import { addSSP, editSSP, getAllBidder, getById} from '../../../api/SSP'

    const types = [
        {
            value: 'com.jacamars.dsp.rtb.exchanges.adx.DoubleClick',
            text: 'adx',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.google.OpenRTB',
            text: 'google',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.openx.OpenX',
            text: 'openx',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.appnexus.Appnexus',
            text: 'appnexus',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Adventurefeeds',
            text: 'adventurefeeds',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Adprudence',
            text: 'adprudence',
        }, {
            value: 'com.jacamars.dsp.rtb.exchanges.AdMedia',
            text: 'admedia',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Atomx',
            text: 'atomx',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.bidswitch.Bidswitch',
            text: 'bidswitch',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Cappture',
            text: 'cappture',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Citenko',
            text: 'citenko',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.C1XUS',
            text: 'c1xus',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.C1X',
            text: 'c1x',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Epomx',
            text: 'epomx',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Fyber',
            text: 'fyber',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Generic',
            text: 'generic',
        }, {
            value: 'com.jacamars.dsp.rtb.exchanges.Kadam',
            text: 'kadam',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Pubmatic',
            text: 'pubmatic',
        }, {
            value: 'com.jacamars.dsp.rtb.exchanges.Privatex',
            text: 'privatex',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Republer',
            text: 'republer',
        }, {
            value: 'com.jacamars.dsp.rtb.exchanges.Stroer',
            text: 'stroer',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Smartyads',
            text: 'smartyads',
        }, {
            value: 'com.jacamars.dsp.rtb.exchanges.SSPHwy',
            text: 'ssphwy',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Smaato',
            text: 'smaato',
        }, {
            value: 'com.jacamars.dsp.rtb.exchanges.Taggify',
            text: 'taggify',
        },
        {
            value: 'com.jacamars.dsp.rtb.exchanges.Gotham',
            text: 'gotham',
        },];

    /*let textList =  ["adx", "google", "openx", "appnexus", "adventurefeeds", "adprudence", "admedia", "atomx", "bidswitch", "cappture", "citenko", "c1xus", "c1x", "epomx", "fyber", "generic", "kadam", "pubmatic", "privatex", "republer", "stroer", "smartyads", "ssphwy", "smaato", "taggify", "gotham"]*/

    let textList =  ["generic"]


    export default {
        data() {
            return {
                form: this.$form.createForm(this),
                userByCompanyDefault: '',
                loading: false,
                userId: this.$route.params.userId || "",

                bidList: [{from: 'all'}],
                types,
                textList,

                isEIkey: true,
                isAdd: true, //默认添加
            }
        },
        methods: {
            validateSSPName(rule, value, callback) {
                if (value) {
                    if (!/^[A-Za-z0-9]+$/.test(value)) {
                        //待修改
                        callback('SSP名称只能英文加数字')
                    }
                }
                callback()
            },
            filterOption(input, option) {
                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
            },
            handleSubmit(e) {
                e.preventDefault();
                this.form.validateFields((err, values) => {
                    if (!err) {
                        values.usesEncodedAdm = !values.usesEncodedAdm; //取反
                        values.isActive = values.isActive ? values.isActive: false;
                        this.addSSPServe(values)
                    }
                })
            },

            addSSPServe(values) {
                this.loading = true;
                if (this.isAdd) {
                    this.$confirm({
                        title: this.$t('pro.ssp.okEd'),
                        content: this.$t('pro.ssp.okTitle'),
                        okText: this.$t('pro.public.buttonYes'),
                        cancelText: this.$t('pro.public.buttonNo'),
                        onOk: () => {
                            addSSP(values).then(res => {
                               this.result(res)
                            }).finally(() => {
                                this.loading = false;
                            })
                        },
                        onCancel: ()=> {
                            this.loading = false;
                        },
                    });
                }else {
                    editSSP(values).then(res => {
                        this.result(res)
                    }).finally(() => {
                        this.loading = false;
                    })
                }
            },

            //接口成功时候回调函数
            result(res) {
                let { code, data } = res.data;
                if (code == 200 && data) {
                    this.$message.success(this.$t('pro.public.buttonSaveEd'), 2).then(() => {
                        this.$router.push({ path: "/admin/ssp/list"});
                    })
                }
            },

            typeChange(value) {
                if (value === "adx" || value === "google" || value === "openx" ) {
                    this.isEIkey = true
                }else  {
                    this.isEIkey = false
                }
            },

            changeUserByCompany(id) {
                this.$nextTick(() => {
                    this.userId = id
                })
            },

            getbidList() {
                getAllBidder().then(res => {
                    let {code, data} = res.data || {};
                    if (code === '200') {
                        this.bidList = data.length > 0 ? data : [{from: "all"}];
                    }
                })
            },

            gitByIdSSP(id){
                this.$nextTick(() => {
                    getById(id).then(res => {
                        let { data, code } = res.data;
                        if (code == 200) {
                            for(let [key, value] of Object.entries(data || {})) {
                                if( key === 'trafficCategory') this.typeChange(value);
                                if( key === 'usesEncodedAdm') value = !value;
                                this.form.setFieldsValue({ [key]: value });
                            }
                        }
                    })
                })
            }
        },
        computed: {
            routes() {
                return [
                    {
                        path: "/admin/ssp/list",
                        breadcrumbName: this.$t('pro.ssp.title')
                    },
                    {
                        path: "second",
                        breadcrumbName: this.$t('pro.ssp.editH')
                    }
                ];

            },

            userByCompanys() {
                let muserList =  this.userByCompany.map(company => {
                    return {
                        id: company.id,
                        value:`${company.company} | ${company.firstName} | ${company.lastName} | ID#${company.id} | $${Math.floor(company.surplusAmount * 100) / 100 || 0}`,
                    };
                });
                let id = this.$route.params.userId || 0;

                muserList.find((item) => {
                    if(item.id == id) {
                        this.$nextTick(() => {
                            this.form.setFieldsValue({'userId': item.value });
                        })
                    }
                });
                return muserList
            },

            userByCompany() {
                return this.$store.getters.userByCompany || [];
            },
        },


        created() {
            this.getbidList();
        },

        mounted() {
            let { id } = this.$route.params || {};
           if (id != 0) {
               this.isAdd = false;
               this.gitByIdSSP(id);
           }else {
               this.isAdd = true;
           }
        }
    }
</script>

<style lang="less">
    .addtransaction-grid {
        grid-template-columns: repeat(3, 1fr);
    }
    @media screen and (max-width: 992px) {
        .addtransaction-grid {
            grid-template-columns: repeat(2, 1fr);
        }
    }
    @media screen and (max-width: 768px) {
        .addtransaction-grid {
            grid-template-columns: repeat(1, 1fr);
        }
    }
</style>
